import _ from 'lodash'
import ebus from 'libs/ebus.js'
import {multimediaApi, mediaPhyApi} from '../../api.js'
import * as types from '../mutation-types'

//vid layout
function makeVidLayout(vidLayout) {
  vidLayout._checked = false
  vidLayout.multiScreen = vidLayout.multiScreenX + 'x' + vidLayout.multiScreenY
}

export function doLoadVidLayouts({dispatch, state}, {init = false} = {}) {
  if (init && state.vidlayout.init) {
    return
  }
  dispatch(types.REFRESH_VID_LAYOUTS_START)
  multimediaApi.getItems('vidLayouts').then(function(res) {
    if (res && res.data && res.data.code === 0) {
      var vidLayouts = res.data.data.vidLayouts
      _.forEach(vidLayouts, (item) => {
        makeVidLayout(item)
      })
      dispatch(types.SET_VID_LAYOUTS, vidLayouts)
    }
    dispatch(types.REFRESH_VID_LAYOUTS_END)
  })
}

export function setVidLayoutChecked({dispatch}, id, val) {
  dispatch(types.SET_VID_LAYOUT_CHECKED, id, val)
}

export function setVidLayoutAllUnchecked({dispatch}) {
  dispatch(types.SET_VID_LAYOUT_ALL_UNCHECKED)
}

//lcd window
export function setLcdTopoDev({dispatch}, val) {
  dispatch(types.SET_LCD_TOPO_DEV, val)
}

export function updateLcdModes({dispatch, state}) {
  let topoDev = state.lcd.topoDev
  if (topoDev.topoId < 0) {
    return
  }
  if (!topoDev.devModel.includes('lcdwall')) {
    return
  }
  mediaPhyApi.setDevId(topoDev.topoId)
  mediaPhyApi.sendCmd('getModes').then(function(res) {
    if (res && res.data && res.data.code === 0) {
      var modes = []
      if (res.data.data.modes) {
        modes = res.data.data.modes
      }
      dispatch(types.SET_LCD_MODES, modes)
    }
  })  
}

export function setLcdModeId({dispatch}, val) {
  dispatch(types.SET_LCD_MODE_ID, val)
}

export function setLcdVTopoId({dispatch}, val) {
  dispatch(types.SET_LCD_V_TOPO_ID, val)
}

export function getLcdCfg({dispatch, state}) {
  let topoDev = state.lcd.topoDev
  if (topoDev.topoId < 0) {
    return
  }
  mediaPhyApi.setDevId(topoDev.topoId)
  mediaPhyApi.getCfg().then(function(res) {
    if (res && res.data && res.data.code === 0) {
      let _info = res.data.data._info
      _info.hasOwnProperty('modeId') && dispatch(types.SET_LCD_MODE_ID, _info.modeId)
      _info.hasOwnProperty('switchLayout') && dispatch(types.SET_LCD_SWITCH_LAYOUT, _info.switchLayout)
    }
  }) 
}